package com.laughing.httpserver.core;

import com.laughing.httpserver.config.HttpServerProperties;
import com.laughing.httpserver.handler.SocketHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author laughing.sheng <laughing1917@yeah.net/>
 * @date 2018/1/25
 */
@Slf4j
@Component
public class BioBootStrap extends BootStrap {

    private static Executor executor= Executors.newFixedThreadPool(10);

    @Autowired
    private HttpServerProperties serverProperties;
    @Autowired
    private SocketHandler socketHandler;

    @PostConstruct
    @Override
    public void init(){
        super.backlog=serverProperties.getBacklog();
        super.host=serverProperties.getHost();
        super.port=serverProperties.getPort();
    }

    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(port, backlog, InetAddress.getByName(host));
            while (true){
                Socket socket = serverSocket.accept();
                executor.execute(()->
                    socketHandler.handle(socket)
                );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
